package persistence;

// default package
// Generated Oct 31, 2014 5:34:05 PM by Hibernate Tools 4.0.0

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import entity.Profile;
import entity.Tenant;

/**
 * Home object for domain model class Tenant.
 * @see .Tenant
 * @author Hibernate Tools
 */
@Stateless
public class TenantDAO {

	private static final Log log = LogFactory.getLog(TenantDAO.class);

	Session session;
	Transaction tx;

	public void persist(Tenant transientInstance) throws Exception {
		log.debug("persisting Tenant instance");
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			session.persist(transientInstance);
			log.debug("persist successful");
		} catch (Exception ex) {
			session.close();
			if (tx != null) {
				tx.rollback();
			}
			log.error("persist failed", ex);
			throw ex;
		}
	}

	public void remove(Tenant persistentInstance) throws Exception {
		log.debug("removing Tenant instance");
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			session.delete(persistentInstance);
			tx.commit();
			log.debug("remove successful");
		} catch (Exception ex) {
			session.close();
			if (tx != null) {
				tx.rollback();
			}
			log.error("remove failed", ex);
			throw ex;
		}
	}

	public Tenant merge(Tenant detachedInstance) throws Exception {
		log.debug("merging Tenant instance");
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			Tenant result = (Tenant) session.merge(detachedInstance);
			tx.commit();
			log.debug("merge successful");
			return result;
		} catch (Exception ex) {
			session.close();
			if (tx != null) {
				tx.rollback();
			}
			log.error("merge failed", ex);
			throw ex;
		}
	}

	public Tenant findById(String name) throws Exception {
		log.debug("getting Tenant instance with id: " + name);
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			
			Query query = session.createQuery("from Tenant where name ='"
					+ name  + "'");
			List<Tenant> list = query.list();
			tx.commit();
			log.debug("get successful");
			return list.get(0);
		} catch (Exception ex) {
			session.close();
			if (tx != null) {
				tx.rollback();
			}
			log.error("persist failed", ex);
			throw ex;
		}
	}
}
